<template>
  <el-card style="width: 100%">
    <el-table :data="buyCarList" style="width: 100%">
      <el-table-column prop="id" label="序号" flex="1" align="center" />
      <el-table-column prop="title" label="名称" flex="1" align="center" />
      <el-table-column prop="price" label="价格" flex="1" align="center" />
      <el-table-column prop="number" label="数量" flex="1" align="center" />
    </el-table>
    <div class="pay">
      <h2>商品的总价是:{{ total }}</h2>
      <el-button type="primary" @click="toPay">结算商品</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { storeToRefs } from 'pinia'
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useBuyCarStores } from '@/stores/stores.js'
import { buyProducts } from '@/api/product.js'
const stores = useBuyCarStores()
const { buyCarList } = storeToRefs(stores)
const { payBuyCarList } = stores
const total = computed(() => {
  return buyCarList.value.reduce((sum, item) => {
    return sum + item.price * item.number
  }, 0)
})

const toPay = async () => {
  const payRes = await buyProducts()
  if (payRes) {
    payBuyCarList()
    ElMessage({
      showClose: true,
      message: '结算成功',
      type: 'success'
    })
  } else {
    ElMessage({
      showClose: true,
      message: '结算失败',
      type: 'error'
    })
  }
}
</script>

<style scoped>
.pay {
  margin-top: 20px;
}
</style>